"""搜索记录数据访问层"""

from datetime import datetime
from typing import List, Tuple

from sqlalchemy import and_, desc, func, select
from sqlalchemy.ext.asyncio import AsyncSession

from module_admin.entity.do.search_record_do import SearchRecord
from module_admin.entity.vo.search_record_vo import SearchRecordQueryModel


class SearchRecordDao:
    """搜索记录 DAO"""

    @classmethod
    async def get_record_list(
        cls,
        db: AsyncSession,
        query_params: SearchRecordQueryModel,
        page_num: int = 1,
        page_size: int = 10
    ) -> Tuple[List[SearchRecord], int]:
        """分页查询搜索记录"""

        conditions = [SearchRecord.del_flag == '0']

        if query_params.keyword:
            conditions.append(SearchRecord.search_keyword.like(f"%{query_params.keyword}%"))
        if query_params.item_id:
            conditions.append(SearchRecord.item_id == query_params.item_id)
        # ⚠️ SearchRecord表没有task_id字段，移除该条件
        # if query_params.task_id:
        #     conditions.append(SearchRecord.task_id == query_params.task_id)
        if query_params.is_new in {'0', '1'}:
            conditions.append(SearchRecord.is_new == (query_params.is_new == '1'))
        # ⚠️ SearchRecord表没有is_ordered字段，移除该条件（可以通过OrderRecord表查询）
        # if query_params.is_ordered in {'0', '1'}:
        #     conditions.append(SearchRecord.is_ordered == query_params.is_ordered)

        if query_params.start_time:
            start_time = cls._ensure_datetime(query_params.start_time)
            if start_time:
                conditions.append(SearchRecord.create_time >= start_time)
        if query_params.end_time:
            end_time = cls._ensure_datetime(query_params.end_time)
            if end_time:
                conditions.append(SearchRecord.create_time <= end_time)

        condition_expr = and_(*conditions)

        # 查询总数
        total_stmt = select(func.count()).select_from(SearchRecord).where(condition_expr)
        total_result = await db.execute(total_stmt)
        total = total_result.scalar_one() or 0

        # 分页数据
        stmt = (
            select(SearchRecord)
            .where(condition_expr)
            .order_by(desc(SearchRecord.create_time))
            .limit(page_size)
            .offset((page_num - 1) * page_size)
        )

        result = await db.execute(stmt)
        rows = result.scalars().all()

        return rows, total

    @staticmethod
    def _ensure_datetime(value):
        if value is None:
            return None
        if isinstance(value, datetime):
            return value
        try:
            return datetime.fromisoformat(str(value))
        except ValueError:
            return None
